package com.chen.framework.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.framework.model.auth.AuthLinkRolePermission;
import com.chen.framework.mapper.AuthLinkRolePermissionMapper;
import com.chen.framework.service.inter.AuthLinkRolePermissionService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: ~龙~
 * @date: 2023/6/13 17:15
 **/
@Service
@AllArgsConstructor
public class AuthLinkRolePermissionServiceImpl extends ServiceImpl<AuthLinkRolePermissionMapper, AuthLinkRolePermission> implements AuthLinkRolePermissionService {

    private final AuthLinkRolePermissionMapper authLinkRolePermissionMapper;

    @Override
    public void roleAndPermissionAssociation(List<Long> roleIdList, Set<Long> permissionIdSet) {
        if (CollectionUtil.isEmpty(roleIdList) || CollectionUtil.isEmpty(permissionIdSet)){
            return;
        }

        List<AuthLinkRolePermission> list = list(
                Wrappers.lambdaQuery(AuthLinkRolePermission.class)
                        .in(AuthLinkRolePermission::getRoleId, roleIdList)
                        .in(AuthLinkRolePermission::getPermissionId, permissionIdSet)
        );
        // 根据角色id分组
        Map<Long, List<AuthLinkRolePermission>> grouMap = list.stream()
                .collect(Collectors.groupingBy(AuthLinkRolePermission::getRoleId));
        // 避免角色没有关联关系时的BUG问题
        for (Long roleId : roleIdList) {
            grouMap.putIfAbsent(roleId,new ArrayList<>());
        }

        List<AuthLinkRolePermission> saveList = new ArrayList<>();
        for (Long roleId : grouMap.keySet()) {
            Map<Long,String> map = new HashMap<>();
            grouMap.get(roleId).forEach(rp -> map.put(rp.getPermissionId(),""));

            Set<Long> perIdSet = new HashSet<>(permissionIdSet);
            // 删除已存在关联关系的权限id
            perIdSet.removeIf(perId -> map.get(perId) != null);
            for (Long perId : perIdSet) {
                AuthLinkRolePermission rp = new AuthLinkRolePermission();
                rp.setRoleId(roleId);
                rp.setPermissionId(perId);
                saveList.add(rp);
            }
        }

        if (saveList.size() > 0){
            authLinkRolePermissionMapper.insertBatchSomeColumn(saveList);
        }
    }

    @Override
    public Set<Long> getPermissionIdSet(Set<Long> roleIdSet) {
        if (CollectionUtil.isEmpty(roleIdSet)){
            return new HashSet<>();
        }
        return list(
                Wrappers.lambdaQuery(AuthLinkRolePermission.class).in(AuthLinkRolePermission::getRoleId, roleIdSet)
        ).stream().map(AuthLinkRolePermission::getPermissionId).collect(Collectors.toSet());
    }
}
